package org.smartercontext.local.servlets;

import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.smartercontext.contextmger.contextsphere.ContextSphereController;


/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public LoginServlet() {
        super();
        // TODO Auto-generated constructor stub
    }
    
    protected void processRequest(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        response.setContentType("text/html;charset=UTF-8");
        PrintWriter out = response.getWriter();
        
        try{
        	
        	        		
        		String username = request.getParameter("username");
        		String password = request.getParameter("password");
        		
        		if(username!=null & password!=null){
        			       			
        			ContextSphereController csc = new ContextSphereController();
        			boolean exists = csc.validateUser(username, password);
        			
        			if(exists){
        				HttpSession session = request.getSession(true);
        				session.setAttribute("username", username);
        				System.out.println(session.getAttribute("username"));
        				response.sendRedirect("index.jsp");
        			}else{
        				response.sendRedirect("login.jsp?Err=2");
        			}
        			
        		}else{
        			response.sendRedirect("login.jsp?Err=1");
        		}
        	
        }finally{
        	out.close();
        }
        
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		processRequest(request, response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		processRequest(request, response);
	}

}
